<template>
	<div style="padding:0 37px 0 44px">	
		<div class="breadcrumb-father">
			<div class="new-breadcrumb">
				
				<router-link  :to="{path:'/welcome'}">
					<img src="../../assets/imgs/Home.png" alt="">
				</router-link>
				<!-- <a href="javascript:void(0)">
				</a> -->
				<span>{{$t('newcash.Withdrawal1')}}</span>
				<span class="arrow">></span>
				<!-- <a href="javascript:void(0)">
				</a> -->
				<span>{{$t('newcash.Withdrawal')}}</span>
			</div>
		</div>

		<div class="card-table">
			<div class="card-table-title">
				<svg aria-hidden="true" class="svg-icon svg-title-icon">
					<use xlink:href="#icon-shanghutixian"></use>
				</svg>
				<span>{{$t('newcash.Withdrawal')}}</span>
			</div>
			<div class="search">
				<div class="search-input">
					<div class="date-wrapper">
						<label>{{ $t('cash.applicationStartDate') }}</label>
						<div class="date-line"></div>
						<el-date-picker v-model="searchCashData.startDate" value-format="yyyy-MM-dd" @keyup.enter.native="handleFilter(0)" :editable=false clearable type="date"></el-date-picker>
					</div>
					<div>
						<label>{{ $t('cash.applicationEndDate') }}</label>
						<el-date-picker v-model="searchCashData.endDate" value-format="yyyy-MM-dd" @keyup.enter.native="handleFilter(0)" :editable=false clearable type="date"></el-date-picker>
					</div>
					<div>
						<label>{{$t('newcash.agentOrMerchantName')}}</label>
						<el-input v-model="searchCashData.merchantName" clearable :maxlength=100 @keyup.enter.native="handleFilter(0)"></el-input>
					</div>
					<div>
						<label>{{$t('newcash.agentOrMerchantID')}}</label>
						<el-input v-model="searchCashData.merchantNumber" clearable :maxlength=100 @keyup.enter.native="handleFilter(0)"></el-input>
					</div>
					<div>
						<label>{{ $t('newcash.withdrawStatus') }}</label>
						<el-select :placeholder="$t('placeH.All')" popper-class="el-select-custom" @keyup.enter.native="handleFilter(0)" v-model="searchCashData.state" clearable>
							<el-option value="0" :label="$t('newcash.pending')"></el-option>
							<el-option value="1" :label="$t('newcash.approved')"></el-option>
							<el-option value="2" :label="$t('newcash.rejected')"></el-option>
							<el-option value="3" :label="$t('newcash.paid')"></el-option>
						</el-select>
					</div>
					<div class="search-btn-group">
						<el-button class="blue-btn mini2-btn" @click="handleFilter(0)">{{$t('button.search')}}</el-button>
						<el-button class='blue-btn mini2-btn' @click='delSelect()'>{{$t('button.Reset')}}</el-button>
					</div>
				</div>
			</div>
			<!--提现列表-->
			<template>
				<div class="table-border">
					<div class="search-result-head">
						<span>{{ searchInfo }}</span>
						<span style="float:right;">
							<a href="javascript:void(0)" @click='export2Excel()' :title="$t('button.SaveResult')"><icon-svg icon-class="daochu"></icon-svg></a> 
              				<a href="javascript:void(0)" @click="refresh()" :title="$t('button.Refresh')"><icon-svg icon-class="shuaxin" id="refresh_icon"></icon-svg></a>
              			</span>
            		</div>
					<el-table border :key='tableKey' :data='withdrawCashDatas' border fit style="width: 100%;" height=500 v-loading="loading" :element-loading-text="$t('button.loading')" element-loading-background="rgba(255, 255, 255, 1)">
						<el-table-column align="center" :label="$t('index.Number')" fixed="left" width="70px" type='index'> </el-table-column>
						<el-table-column width="200px" align="center" :label="$t('newcash.requestDate')" prop="startTime">
						</el-table-column>
						<el-table-column width="220px" align="center" :label="$t('newcash.agentOrMerchantName')" prop="mername" class-name="title_name" :formatter="judgeMerName">
						</el-table-column>
						<el-table-column prop="merchantNumber" :label="$t('newcash.agentOrMerchantID')" width="200" :formatter="judgeNumber"> 
						</el-table-column>
						<el-table-column width="100px" align="center" :label="$t('newcash.bankName')" prop="bankname">
						</el-table-column>
						<el-table-column width="150px" align="center" :label="$t('newcash.bankAccount')" prop="bankCard">
						</el-table-column>
						<el-table-column width="180px" align="center" :label="$t('newcash.accountName')" prop="drawname">
						</el-table-column>
						<el-table-column width="220px" align="center" :label="$t('newcash.withdrawAmount')" prop="withdrawal_amount" :formatter='judgeMoney'>
						</el-table-column>
						<el-table-column width="180px" align="center" :label="$t('newcash.withdrawType')" prop="type" :formatter='judgeType'>
						</el-table-column>
						<!-- <el-table-column width="150px" align="center" :label="$t('newcash.withdrawFee')" prop="poundage" :formatter="judgePoundage">
						</el-table-column> -->
						<!-- <el-table-column width="180px" align="center" :label="$t('newcash.remitAmount')" prop="amount" :formatter="judgeAmount">
						</el-table-column> -->
						<el-table-column width="180px" align="center" :label="$t('inputBox.status')" prop="state" :formatter='judge'>
						</el-table-column>
						<el-table-column width="170px" align="center" :label="$t('cash.auditTime')" prop="inspectTime">
						</el-table-column>
						<el-table-column width="170px" align="center" :label="$t('newcash.paymentTime')" prop="remitTime">
						</el-table-column>
					</el-table>
				</div>
			</template>	
		</div>
  		
  		<div class="pagination-container">
    		<el-pagination :total="res.total" background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="searchCashData.page" :page-sizes="[15,20,30, 50]" :page-size="searchCashData.pageSize" layout="total, sizes, prev, pager, next, jumper"></el-pagination>
  		</div>
	</div>
</template>

<script>
	import { withdrawCashAll,checkCash,withdrawCashPay } from 'api/merchantWithdrawCash/index';
	import { Message , MessageBox} from 'element-ui';
	import XLSX from "xlsx";
	import XLSX_SAVE from "file-saver";

	function s2ab(s) {
	const buf = new ArrayBuffer(s.length);
	const view = new Uint8Array(buf);
	for (let i = 0; i !== s.length; ++i) {
		view[i] = s.charCodeAt(i) & 0xff;
	}
		return buf;
	}
	export default {
		name: 'WithdrawalCash',
		data(){
			return {
			    tableKey: 0,
			    res:[],
				withdrawCashDatas:[],
				//按条件搜索订单所需参数
				searchCashData:{
					state:'',
					merchantName:'',
					merchantNumber:'',
					startDate:'',
					endDate:'',
					page:1,
					pageSize:15
				},
				list: null,
//			    total: null,//查询得知总订单数
			    //第一次进提现
			    oneCashData:{
			    	page:1,
					pageSize:15
				},
				degIndex:1,
				rorateFlag:true,
				searchInfo:'',
				exportSearchData:{},
				currency:undefined,
				oldPage: null,
                loading: true,
                companyId:localStorage.getItem('companyId'),
			}
		},
		watch:{
		  'searchCashData.page':function(newVal,oldVal){
		      this.oldPage = oldVal;
		  },
		},
		created () {
			this.getWithdrawCashList(this.oneCashData);
			this.searchInfo = this.$t('newcash.Withdrawal');

			if (this.companyId == '1') this.currency = 'HK$ ';
            if (this.companyId == '2') this.currency = 'A$ ';
		},
		methods: { 
			refresh(){
				const _that = this;
				if(this.rorateFlag){
					document.getElementById('refresh_icon').style.transform = 'rotate('+ this.degIndex * 360 +'deg)';
					this.handleFilter(1);
					this.rorateFlag = false;
					setTimeout(function (param) { _that.rorateFlag = true;_that.degIndex++; },1000);
				}
			},
			//清空筛选条件
			delSelect(){
				this.searchCashData.state=undefined;
				this.searchCashData.merchantName=undefined;
				this.searchCashData.merchantNumber=undefined;
				this.searchCashData.startDate=undefined;
				this.searchCashData.endDate=undefined;

				this.searchInfo =  this.$t('newcash.Withdrawal');
				this.handleFilter(1);
			},
			judgeMerName(row) {
				return row.mername ? row.mername : row.distributorName;
			},
			judgeNumber(row) {
				return row.merchantNumber ? row.merchantNumber : row.distributorNumber;
			},
			// 格式化打款金额(V2.8丢弃)
			// judgeAmount(row){
			// 	if(row.hasOwnProperty('amount')){
			// 		let formatAmount = row.amount;
			// 		return formatAmount = this.currency + this.fmoney(formatAmount,2);
			// 	};
			// },
			// 格式化手续费
			judgePoundage(row){
				if(row.hasOwnProperty('poundage')){
					let formatPoundage = row.poundage;
					return formatPoundage = this.currency + this.fmoney(formatPoundage,2);
				};
			},
			//格式化显示数据
			judge(data){
				let state = data.state
				if(state === '0'){
					return state = this.$t('newcash.pending')
				}
				if(state === '1'){
					return state = this.$t('newcash.approved')
				}
				if(state === '2'){
					return state = this.$t('newcash.rejected')
				}
				if(state === '3'){
					return state = this.$t('newcash.paid')
				}
			},
			//格式化提现金额
			judgeMoney(row){
				let formatMoney = row.withdrawal_amount;
				// return formatMoney;
				return formatMoney = this.currency + this.fmoney(formatMoney,2);
			},
			// 格式化金额
			fmoney(s, n){   
				if( s === "" || s === undefined ) return s = "0.00";
				s = s / 100;
				n = n > 0 && n <= 20 ? n : 2;   
				s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";   
				var l = s.split(".")[0].split("").reverse(),   
				r = s.split(".")[1];   
				let t = "";   
				for(let i = 0; i < l.length; i ++ )   
				{   
					t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");   
				}   
				return t.split("").reverse().join("") + "." + r;
			},
			//格式化显示数据
			judgeType(data){
				return data.type == '0' ? this.$t('cash.check') : this.$t('cash.onlineBanking');
			},
			//封装了提现查询的方法
			getWithdrawCashList(data,str){
				const _that = this;
				withdrawCashAll(data).then(res => {
					// console.log('提现查询返回的数据--------');
					this.res = res.value;
					// console.log(res.value);
					this.withdrawCashDatas = res.value.rows;

					// 如果是分页触发，循环去除选中样式，对点击后的项数添加选中样式
					if( str == 'CurrentChange' ){
					  let obj = $('.el-pager .number');
					  for( let i = 0; i < obj.length; i++){
					      if($(obj[i]).html() == this.searchCashData.page) {
					        $(obj[i]).addClass('active');
					      } else {
					        $(obj[i]).removeClass('active');
					      }
					  }
					}

					setTimeout(function(){
						const title_name_arr = $(".el-table__body-wrapper .title_name .cell");
						for(let j = 0;j<title_name_arr.length;j++){
							$(title_name_arr[j]).attr('title',$(title_name_arr[j]).html());
						}

						// 隐藏载入提示层
						_that.loading = false;
					},500)
				}).catch(error=>{
					console.log(error);
				})
			},
			// 判断字符串长度的方法
			getStrL(str){
				let l = str.length; 
				let blen = 0; 
				for(let i=0; i<l; i++) { 
					if ((str.charCodeAt(i) & 0xff00) != 0) { 
						blen ++; 
					} 
					blen ++; 
				}
				return blen;
			},
			//点击搜索 查询提现列表
		    handleFilter(sign,str) {

		    	// 显示载入提示层
		    	this.loading = true;

				if(sign === 0) this.searchInfo =  this.$t('index.searchResults');
				this.exportSearchData = {};
				$.extend(this.exportSearchData, this.searchCashData);
		    	this.formatObj(this.exportSearchData);
		    	// console.log('设备查询向后台发送的数据')
		    	// console.log(searchCashData)
			    this.getWithdrawCashList(this.exportSearchData,str);

			    if( str == 'CurrentChange' ){
			      // 获取所有分页项数，循环去除选中样式，对点击前的项数添加选中样式
			      let obj = $('.el-pager .number');
			      for( let i = 0; i < obj.length; i++){
			          if($(obj[i]).html() == this.oldPage) {
			            console.log(this.oldPage);
			            $(obj[i]).addClass('active');
			          } else {
			            $(obj[i]).removeClass('active');
			          }
			      }
			    }
		    },
			//pageSize 改变时会触发
		    handleSizeChange(val) {
		        this.searchCashData.pageSize = val;
		        this.handleFilter(1);
		    },
		    //currentPage 改变时会触发
		    handleCurrentChange(val) {
		        this.searchCashData.page = val;
		        this.handleFilter(1,'CurrentChange');
			},
			//导出表格
			export2Excel() {
				require.ensure([], () => {
					let listQuery = {};
					$.extend(listQuery, this.exportSearchData);
					listQuery.pageSize = this.res.total;
					withdrawCashAll(listQuery).then(res => {
						const { export_json_to_excel } = require("../../vendor/Export2Excel");
						const tHeader = [
							this.$t('newcash.requestDate'),
							this.$t('newcash.agentOrMerchantName'),
							this.$t('newcash.agentOrMerchantID'),
							this.$t('newcash.bankName'),
							this.$t('newcash.bankAccount'),
							this.$t('newcash.accountName'),
							this.$t('newcash.withdrawAmount')+' '+this.currency,
							this.$t('newcash.withdrawType'),
							// this.$t('newcash.withdrawFee')+' '+this.currency,
							// this.$t('newcash.remitAmount')+' '+this.currency,
							this.$t('newcash.status'),
							this.$t('newcash.approvalTime'),
							this.$t('newcash.paymentTime'),
						]; //对应表格输出的title
						const filterVal = [
							"startTime",
							"mername",
							"merchantNumber",
							"bankname",
							"bankCard",
							"drawname",
							"withdrawal_amount",
							"type",
							// "poundage",
							// "amount",
							"state",
							"inspectTime",
							"remitTime",
						]; // 对应表格输出的数据
						const list = res.value.rows;
						for (let i = 0; i < list.length; i++) {
							// list[i].amount = this.fmoney(list[i].amount,2);
							// list[i].poundage = this.fmoney(list[i].poundage,2);
							list[i].withdrawal_amount = this.fmoney(list[i].withdrawal_amount,2);
							list[i].mername = list[i].mername ? list[i].mername : list[i].distributorName;
							list[i].merchantNumber = list[i].merchantNumber ? list[i].merchantNumber : list[i].distributorNumber;
							// list[i].type = list[i].type ===  '0' ? this.$t('cash.check') : this.$t('cash.onlineBanking');
							if(list[i].state === '0'){
								list[i].state = this.$t('newcash.pending')
							}
							if(list[i].state === '1'){
								list[i].state = this.$t('newcash.approved')
							}
							if(list[i].state === '2'){
								list[i].state = this.$t('newcash.rejected')
							}
							if(list[i].state === '3'){
								list[i].state = this.$t('newcash.paid')
							}
							if(list[i].type === '0'){
								list[i].type = this.$t('cash.check')
							}
							if(list[i].type === '1'){
								list[i].type = this.$t('cash.onlineBanking');
							}
						}
						const data = this.formatJson(filterVal, list);
						export_json_to_excel(tHeader, data, this.$t('newcash.Withdrawal')); //对应下载文件的名字
					});
				});
			},
			formatJson(filterVal, jsonData) {
				return jsonData.map(v => filterVal.map(j => v[j]));
			},
		    formatObj(obj){
				let arr = Object.keys(obj);
				for(let i = 0;i<arr.length;i++){
					if(obj[arr[i]] === ''){
						obj[arr[i]] = null;
					}
				}
			},
		}
	}

</script>

<style scoped>
	.el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
  /*.el-input{
  	width: 200px;
  }*/
</style>